package meterMonitor.controller;

import meterMonitor.biz.MeterBiz;
import meterMonitor.biz.MonitorDayBiz;
import meterMonitor.biz.MonitorDetailBiz;
import meterMonitor.biz.MonitorMonthBiz;
import meterMonitor.consts.ResponseCode;
import meterMonitor.framework.auth.AuthorityType;
import meterMonitor.framework.auth.FireAuthority;
import meterMonitor.model.Meter;
import meterMonitor.model.MonitorDay;
import meterMonitor.model.MonitorDetail;
import meterMonitor.model.Reader;
import meterMonitor.vo.BaseResponseData;
import meterMonitor.vo.RealTimeFlow;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 实时controller
 */
@RequestMapping("monitor")
@RestController
public class MonitorController extends BaseController {
    public static final Logger logger = LoggerFactory.getLogger(MonitorController.class);
    @Autowired
    MonitorDetailBiz monitorDetailBiz;
    @Autowired
    MonitorDayBiz monitorDayBiz;
    @Autowired
    MonitorMonthBiz monitorMonthBiz;
    @Autowired
    MeterBiz meterBiz;

    /**
     * 首页数据展示
     * @param
     * @param
     * @return
     */
    @RequestMapping("index.do")
    @FireAuthority(authorityTypes = AuthorityType.Query)
    private ModelAndView index(ModelAndView mv) {
        return mv;
    }

    /**
     *求水电表的详细数据
     * @param areaId
     * @return
     */
    @RequestMapping("getRealTimeFlow.do")
    @ResponseBody
    @FireAuthority(authorityTypes = AuthorityType.Query)
    private BaseResponseData getRealTimeFlow(Integer areaId,String deviceTypeCode) {
        System.out.println(deviceTypeCode.equals("1"));//true
        BaseResponseData response = new BaseResponseData();
        DecimalFormat df = new DecimalFormat("#0.0");
        DecimalFormat df1 = new DecimalFormat("#0.000");
        if (deviceTypeCode.equals("1")){
            try {
                // 判断时间
                Calendar instance = Calendar.getInstance();//ava中提供了Calendar这个专门用于对日期进行操作的类
                int hour = instance.get(Calendar.HOUR_OF_DAY);
                //设置日期格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                // if (hour < 8) {
                //     instance.add(Calendar.DATE, -1);
                // }
                //获取当前时间
                String day = sdf.format(instance.getTime());

                //当天总数据
                double totalQuantiry = 0D;
                //当天累计标准量
                double standardQuantiry = 0D;
                //当天标准量


                //离线设备 （meter_code）
                Map<Long,String> offlineList = new HashMap<>();

                //存储离线以及时间
                Map<Integer,String> offlineTime=new HashMap<>();

                Map<Integer,String> overflowTime=new HashMap<>();

                Map<Long,String> overflowList = new HashMap<>();


                //查询符合条件的电表
                Meter meter = new Meter();
                meter.setAreaId(areaId);
                //meter.setStatus(10); // 启用设备
                List<Meter> meters = meterBiz.queryMeterWater(meter);
                // 查询读表器的在线状态
                List<RealTimeFlow> list = new ArrayList<>();

                //求当前所有仪器的日标准量的和
                //时分

                //统计日标准总和所有设备按类型分
                List<Meter> mete1=meterBiz.queryAllMeter1();
                for (Meter meter1 : mete1) {
                    standardQuantiry += meter1.getStandard();
                }

                Calendar cal = Calendar.getInstance();
                int hour1 = cal.get(Calendar.HOUR_OF_DAY);
                int minute = cal.get(Calendar.MINUTE);
                double totalStandardNow=(standardQuantiry/1440)*(hour1*60+minute);





                RealTimeFlow realTimeFlow = null;
                for (Meter m : meters) {
                    realTimeFlow = new RealTimeFlow();
                    realTimeFlow.setMeterCode(m.getMeterCode());//设备编码
                    realTimeFlow.setDeviceName(m.getDeviceName());//序号
                    realTimeFlow.setAnotherName(m.getAnotherName());//设备名称
                    realTimeFlow.setStandard(m.getStandard());//日标准量
                    realTimeFlow.setAreaId(m.getAreaId());//设备所属区域id


                    realTimeFlow.setCumulativeStandard(Double.valueOf((df.format((m.getStandard()/1440)*(hour1*60+minute)))));




                    //根据读表器编码查询读表器
                    Reader reader = meterBiz.queryReaderByReaderCode(m.getReaderCode());//读表器编码
                    if (Objects.nonNull(reader)) {
                        //将读到的reader状态传给realTimeFlow
                        realTimeFlow.setStatus(reader.getStatus());
                        // 记录设备离线
                        if (reader.getStatus() == 20) {
                            offlineList.put(m.getMeterCode(),m.getAnotherName());
                            realTimeFlow.setIsNA("N/A");
                        }
                    } else {
                        offlineList.put(m.getMeterCode(),m.getAnotherName());
                        realTimeFlow.setIsNA("N/A");
                    }

                    //根据meter_code查出对应的monitorDetail的详细信息
                    MonitorDetail monitorDetail = monitorDetailBiz.getCurrentByMeterCode(m.getMeterCode());
                    //如果不为空，将设备当前数据传给realTimeFlow中
                    if (Objects.nonNull(monitorDetail)) {
                        realTimeFlow.setCurrentQuantity(monitorDetail.getCurrentQuantiry());
                    } else {
                        offlineList.put(m.getMeterCode(),m.getAnotherName());
                        realTimeFlow.setIsNA("N/A");
                    }


                    //根据meter_code查出对应的日详细数据
                    MonitorDay monitorDay = monitorDayBiz.getCurrentByMeterCode(m.getMeterCode());
                    if (Objects.nonNull(monitorDay)) {
                        //对比当前日期与查到的数据的日期
                        if (monitorDay.getDay().equals(day)) {
                            //刚好日期相等就记录下当日的数据
                            Double intervalQuantity = monitorDay.getIntervalQuantity();
                            // 记录数据超标
                            if (intervalQuantity > (m.getStandard()/1440)*(hour1*60+minute)) {
                                //记录超标的名称
                                overflowList.put(m.getMeterCode(),m.getAnotherName());
                                //记录为超限
                                realTimeFlow.setOverExceedFlow(true);
                            }
                            totalQuantiry += intervalQuantity;

                            realTimeFlow.setIntervalQuantity(intervalQuantity);
                        } else {
                            offlineList.put(m.getMeterCode(),m.getAnotherName());
                            realTimeFlow.setIsNA("N/A");
                        }
                    } else {
                        offlineList.put(m.getMeterCode(),m.getAnotherName());
                        realTimeFlow.setIsNA("N/A");

                    }
                    // 记录最新的数据

                    System.out.println(realTimeFlow.getAreaId()+"818");
                    list.add(realTimeFlow);
                }

                //记录离线警告
                int count=0;
                if (offlineList.size()==0||offlineList==null){
                    System.out.println("无离线");
                }else{
                    for (Map.Entry<Long, String> longStringEntry : offlineList.entrySet()) {
                        List<Meter> meterList=meterBiz.queryTimeByOffline(longStringEntry.getKey());
                        int s=++count;
                        if (meterList==null||meterList.size()==0){
                            offlineTime.put(s,"未知时间"+","+longStringEntry.getValue());
                        }else{ offlineTime.put(s,meterList.get(0).getExceptionTime()+","+meterList.get(0).getAnotherName());
                        }
                    }
                }
                //记录超标警告
                int count1=0;
                if (overflowList.size()==0||overflowList==null){
                    System.out.println("wucchaobiao");
                }else{
                    for (Map.Entry<Long, String> longStringEntry : overflowList.entrySet()) {
                        List<Meter> meterList=meterBiz.queryTimeByExcessive(longStringEntry.getKey());
                        int s1=++count;
                        if (meterList==null||meterList.size()==0){
                            overflowTime.put(s1,"未知时间"+","+longStringEntry.getValue());
                        }else{
                           overflowTime.put(s1,meterList.get(0).getExceptionTime()+","+meterList.get(0).getAnotherName());
                        }
                    }
                }


                Map<String, Object> result = new HashedMap();

                result.put("date", day); // 显示日期
                //仪器日用总量

                //将总量保留两位小数
                BigDecimal bd = new BigDecimal(totalQuantiry);
                totalQuantiry = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                Double rate = standardQuantiry != 0 ? ((Double.valueOf(df.format(totalStandardNow)) - totalQuantiry) / Double.valueOf(df.format(totalStandardNow))) : 0d;



                result.put("total", meters.size()); // 电表总数
                result.put("rate", String.format(df1.format(rate)));// 节约率
                result.put("offline", offlineTime);// 离线警告
                result.put("offlines",offlineTime.size());//离线个数
                result.put("overflow", overflowTime);// 超标警告
                result.put("overflows",overflowTime.size());//超标个数
                result.put("list", list);// 节约率
                result.put("standardQuantiry", Double.valueOf(df.format(totalStandardNow)));
                result.put("standardQuantiry1", standardQuantiry);
                result.put("totalQuantiry",totalQuantiry);
                response.setData(result);
                response.setCode(ResponseCode.SUCCESS);
            } catch (Exception ex) {
                logger.error("查询综合数据异常!", ex);
                response.setCode(ResponseCode.DEFAULT_EXCEPTION);
                response.setMessage("系统异常！请联系管理员");
            }
        } else if(deviceTypeCode.equals("0")){
            try {
                // 判断时间
                Calendar instance = Calendar.getInstance();//ava中提供了Calendar这个专门用于对日期进行操作的类
                int hour = instance.get(Calendar.HOUR_OF_DAY);
                //设置日期格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                // if (hour < 8) {
                //     instance.add(Calendar.DATE, -1);
                // }
                //获取当前时间
                String day = sdf.format(instance.getTime());

                //当天总数据
                double totalQuantiry = 0D;
                //当天标准量
                double standardQuantiry = 0D;

                //离线设备 （meter_code）
                Map<Long,String> offlineList = new HashMap<>();

                //存储离线以及时间
                Map<Integer,String> offlineTime=new IdentityHashMap();

                Map<Long,String> overflowList = new HashMap<>();
                Map<Integer,String> overflowTime=new IdentityHashMap();

                //查询符合条件的电表
                Meter meter = new Meter();
                meter.setAreaId(areaId);
                //meter.setStatus(10); // 启用设备
                List<Meter> meters = meterBiz.queryElectricityMeter(meter);
                // 查询读表器的在线状态
                List<RealTimeFlow> list = new ArrayList<>();

                RealTimeFlow realTimeFlow = null;
                Calendar cal = Calendar.getInstance();
                int hour1 = cal.get(Calendar.HOUR_OF_DAY);
                int minute = cal.get(Calendar.MINUTE);
                for (Meter m : meters) {
                    realTimeFlow = new RealTimeFlow();
                    realTimeFlow.setMeterCode(m.getMeterCode());//设备编码
                    realTimeFlow.setDeviceName(m.getDeviceName());//序号
                    realTimeFlow.setAnotherName(m.getAnotherName());//设备名称
                    realTimeFlow.setStandard(m.getStandard());//日标准量
                    realTimeFlow.setAreaId(m.getAreaId());//设备所属区域id

                    realTimeFlow.setCumulativeStandard(Double.valueOf((df.format((m.getStandard()/1440)*(hour1*60+minute)))));

                    //根据读表器编码查询读表器
                    Reader reader = meterBiz.queryReaderByReaderCode(m.getReaderCode());//读表器编码
                    if (Objects.nonNull(reader)) {
                        //将读到的reader状态传给realTimeFlow
                        realTimeFlow.setStatus(reader.getStatus());
                        // 记录设备离线
                        if (reader.getStatus() == 20) {
                            offlineList.put(m.getMeterCode(),m.getAnotherName());
                            realTimeFlow.setIsNA("N/A");
                        }
                    } else {
                        offlineList.put(m.getMeterCode(),m.getAnotherName());
                        realTimeFlow.setIsNA("N/A");
                    }

                    //根据meter_code查出对应的monitorDetail的详细信息
                    MonitorDetail monitorDetail = monitorDetailBiz.getCurrentByMeterCode(m.getMeterCode());
                    //如果不为空，将设备当前数据传给realTimeFlow中
                    if (Objects.nonNull(monitorDetail)) {
                        realTimeFlow.setCurrentQuantity(monitorDetail.getCurrentQuantiry());
                    } else {
                        offlineList.put(m.getMeterCode(),m.getAnotherName());
                        realTimeFlow.setIsNA("N/A");
                    }



                    //根据meter_code查出对应的日详细数据
                    MonitorDay monitorDay = monitorDayBiz.getCurrentByMeterCode(m.getMeterCode());
                    if (Objects.nonNull(monitorDay)) {
                        //对比当前日期与查到的数据的日期
                        if (monitorDay.getDay().equals(day)) {
                            //刚好日期相等就记录下当日的数据
                            Double intervalQuantity = monitorDay.getIntervalQuantity();
                            // 记录数据超标
                            if (intervalQuantity >( m.getStandard()/1440)*(hour1*60+minute)) {
                                //记录超标的名称
                                overflowList.put(m.getMeterCode(),m.getAnotherName());
                                //记录为超限
                                realTimeFlow.setOverExceedFlow(true);
                            }
                            totalQuantiry += intervalQuantity;
                            standardQuantiry += m.getStandard();
                            realTimeFlow.setIntervalQuantity(intervalQuantity);
                        } else {
                            offlineList.put(m.getMeterCode(),m.getAnotherName());
                            realTimeFlow.setIsNA("N/A");
                        }
                    } else {
                        offlineList.put(m.getMeterCode(),m.getAnotherName());
                        realTimeFlow.setIsNA("N/A");

                    }
                    // 记录最新的数据

                    System.out.println(realTimeFlow.getAreaId()+"1713");
                    list.add(realTimeFlow);
                }

                //求当前所有仪器的日标准量的和


                double totalStandardNow=Double.valueOf(df.format( (standardQuantiry/1440)*(hour1*60+minute)));



                //记录离线警告
                int count2=0;
                if (offlineList.size()==0||offlineList==null){
                    System.out.println("无离线");

                }else{
                    for (Map.Entry<Long, String> longStringEntry : offlineList.entrySet()) {
                        List<Meter> meterList=meterBiz.queryTimeByOffline(longStringEntry.getKey());
                        int s2=++count2;
                        if (meterList==null||meterList.size()==0){
                            offlineTime.put(s2,"未知时间"+","+longStringEntry.getValue());
                        }else{
                           offlineTime.put(s2,meterList.get(0).getExceptionTime()+","+meterList.get(0).getAnotherName());
                        }
                    }
                }

                //记录超标警告

                int count3=0;
                if (overflowList.size()==0||overflowList==null){
                    System.out.println("wucchaobiao");
                }
                 for (Map.Entry<Long, String> longStringEntry : overflowList.entrySet()) {
                        List<Meter> meterList=meterBiz.queryTimeByExcessive(longStringEntry.getKey());
                        int s3=++count3;
                        if (meterList==null||meterList.size()==0){
                            overflowTime.put(s3,"未知时间"+","+longStringEntry.getValue());
                        }else{
                           overflowTime.put(s3,meterList.get(0).getExceptionTime()+","+meterList.get(0).getAnotherName());

                        }
                 }

                Map<String, Object> result = new HashedMap();
                Double rate = totalStandardNow != 0 ? ((totalStandardNow - totalQuantiry) / totalStandardNow) : 0d;

                result.put("date", day); // 显示日期
                //仪器日用总量

                //将总量保留两位小数
                BigDecimal bd = new BigDecimal(totalQuantiry);
                totalQuantiry = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();



                result.put("total", meters.size()); // 电表总数
                result.put("rate", String.format("%.3f", rate));// 节约率
                result.put("offline", offlineTime);// 离线警告
                result.put("offlines",offlineTime.size());//离线个数
                result.put("overflow", overflowTime);// 超标警告
                result.put("overflows",overflowTime.size());//超标个数
                result.put("list", list);// 节约率
                result.put("standardQuantiry", totalStandardNow);
                result.put("standardQuantiry1", standardQuantiry);

                result.put("totalQuantiry",totalQuantiry);
                response.setData(result);
                response.setCode(ResponseCode.SUCCESS);
            } catch (Exception ex) {
                logger.error("查询综合数据异常!", ex);
                response.setCode(ResponseCode.DEFAULT_EXCEPTION);
                response.setMessage("系统异常！请联系管理员");
            }
        }

        return response;
    }


}
